var creatGameDialog;

$("document").ready(function(){   
    creatGameDialog = $("#create_game_dialog_form")
    .dialog({        
        draggable: false,
        autoOpen: false,
        title: 'Create Game',
        modal: true,
        resizable: false,  
        width: 'auto',
        buttons: [
        {
            text: "Create",            
            click: function(){
                $.ajax({
                    url:"?request=createdGame&time="+document.forms[0].time.value+"&startRule="+document.forms[0].startRule.value,
                    success: function(data){
                        if(data!=null){               
                            //errors to be added
                            $( this ).dialog( "close" );             
                            ajaxCall();
                        }       
                    }
                });
                $( this ).dialog( "close" ); 
               
            }
        },
        {
            text: "Cancel",
            click: function(){
                $(this).dialog("close");
            }
        }
        ]
    });    
    
    $('.gameList').flexigrid({
        width: 600,
        height: 400,
        resizable: false, 
        dataType: 'json',
        colresize: true,
        colModel : [
        {
            display: 'From', 
            name : 'playerName', 
            width : 100, 
            sortable : true, 
            align: 'center'        
        },

        {
            display: 'Rating', 
            name : 'rating', 
            width : 60, 
            sortable : true, 
            align: 'center'        
        },

        {
            display: 'Time', 
            name : 'time', 
            width : 60, 
            sortable : true, 
            align: 'center'        
        },

        {
            display: 'Start Rule', 
            name : 'startRule', 
            width : 60, 
            sortable : true, 
            align: 'center'        
        },
        
        {
            display: "Join", 
            name : 'join', 
            width : 40, 
            sortable : true, 
            align: 'center'        
        },
        
        {
            display: "Delete", 
            name : 'delete', 
            width : 40, 
            sortable : true, 
            align: 'center'        
        }
        ],
        buttons : [
        {
            name: 'Create Game', 
            bclass: 'add', 
            onpress : createGame
        },		
        {
            separator: true
        }
        ],
        showTableToggleBtn: false,
        title: "List of games",
        maxHeight: 600
    });
    $('.top10PlayerList').flexigrid({
        width: 320,
        height: 260,
        resizable: false, 
        dataType: 'json',
        colresize: true,
        colModel : [
        {
            display: 'Rank', 
            name : 'rank', 
            width : 30, 
            sortable : true, 
            align: 'center'        
        },
        {
            display: 'Nickname', 
            name : 'nickname', 
            width : 125, 
            sortable : true, 
            align: 'center'
        },
        {
            display: 'Rating', 
            name : 'rating', 
            width : 60, 
            sortable : true, 
            align: 'center'        
        }],        
        showTableToggleBtn: false,
        title: "Top 10 players",
        maxHeight: 600
    });
    ajaxCall();
    setInterval( "ajaxCall()", 1000 );
});

function formatTableTop10PlayersResult(data){
    var rows = Array();

    for (var i = 0; i < data.length; i++) {                
        rows.push({
            cell: [
            data[i].rank,
            data[i].nickname,
            data[i].rating
            ]
        });
    }

    return {
        total: data.length,
        page: 1,
        rows: rows
    };
}

function formatTableResults(data){
    var rows = Array();

    for (var i = 0; i < data.length; i++) {
        var joinHyperLink,deleteHyperLink;
        if(data[i].isOwner){
            deleteHyperLink='<a href="?request=deleteGame&from='+data[i].playerName+'&time='+data[i].time+'&startRule='+data[i].startRule+'">delete</a>';
            joinHyperLink='';
        } else {
            deleteHyperLink='';
            joinHyperLink='<a href="?request=joinGame&from='+data[i].playerName+'&time='+data[i].time+'&startRule='+data[i].startRule+'">join</a>';
        }
        rows.push({
            cell: [
            data[i].playerName,
            data[i].rating,
            data[i].time,
            data[i].startRule?"yes":"no",
            joinHyperLink,
            deleteHyperLink
            ]
        });
    }

    return {
        total: data.length,
        page: 1,
        rows: rows
    };
}

function createGame(){    
    creatGameDialog.dialog('open');    
}

function ajaxCall(){
    $.ajax({
        url: "?request=loggedinGameData&rand="+(new Date()).getTime(),
        success: function(data){        
            if(data!=null){
                $(".gameList").flexAddData(formatTableResults(data));
            }
        }
    });
    
    $.ajax({
        url: "?request=joinRequest",
        success: function(data){
            if(data==true)
                window.location="?request=joinGameHost&time="+data.time+"&startRule="+data.startRule;    
        }       
    });
    
    $.ajax({
        url: "?request=top10Players",
        success: function(data){
            if(data!=null){
                $(".top10PlayerList").flexAddData(formatTableTop10PlayersResult(data));
            }                
        }       
    });
}

//createGame
function validateNumOnly(evt) {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[0-9]/;
    if( !regex.test(key) ) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    }
}
function validateFormCreateGame(){
    var time=document.forms["gameCreation"]["time"].value;
    if(time>1200){
        document.getElementById("timeError").innerHTML="The value of time must be less than 1200.";
        return false;
    }
    return true;
}
//create game end
